package com.example.jwt.framework.security.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.example.jwt.common.exception.ServiceException;
import com.example.jwt.framework.security.model.LoginUser;
import com.example.jwt.framework.security.service.SysPermissionService;
import com.example.jwt.project.sys.entity.SysRole;
import com.example.jwt.project.sys.entity.SysUser;
import com.example.jwt.project.sys.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @version 1.0.0
 * @className: MyUserDetailsServiceImpl
 * @description: security具体登录逻辑
 * @author: LiJunYi
 * @create: 2022/7/26 9:11
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(MyUserDetailsServiceImpl.class);

    private final ISysUserService userService;

    private final PasswordService passwordService;

    private final SysPermissionService permissionService;

    /**
     * 构造器注入
     *
     * @param userService       用户服务
     * @param permissionService 许可服务
     * @param passwordService   密码服务
     */
    public MyUserDetailsServiceImpl(ISysUserService userService, PasswordService passwordService, SysPermissionService permissionService)
    {
        this.userService = userService;
        this.passwordService = passwordService;
        this.permissionService = permissionService;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.getByUsername(username);
        if (ObjectUtil.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        // 密码校验扩展：根据业务实现不同功能，如错误3次以上则锁定5分钟(借助redis实现)之类
        passwordService.validate(user);
        // 获取角色
        List<SysRole> roles = permissionService.getRolesByUserId(user);
        user.setRoles(roles);
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(Convert.toLong(user.getId()), 1000L, user, permissionService.getMenuPermission(user));
    }

}
